package com.shenqi.parking.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.http.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 微信小程序access_token获取与缓存服务
 */
@Service
public class WechatAccessTokenService {

    // access_token在Redis中的键名
    private static final String ACCESS_TOKEN_KEY = "wechat:mini:access_token";
    // 获取access_token的接口地址
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    @Autowired
    private RedisCache redisCache;
    // 从配置文件获取小程序appid
    @Value("${wechat.mini.appid}")
    private String appId;
    // 从配置文件获取小程序secret
    @Value("${wechat.mini.secret}")
    private String secret;

    /**
     * 获取有效的access_token
     * 先从Redis获取，如果不存在或已过期则重新获取并缓存
     */
    public String getAccessToken() {
        // 尝试从Redis获取
        String accessToken = redisCache.getCacheObject(ACCESS_TOKEN_KEY);
        // 如果缓存中存在，则直接返回
        if (accessToken != null) {
            return accessToken;
        }

        // 缓存中不存在，调用微信接口获取
        accessToken = fetchAccessTokenFromWechat();
        redisCache.setCacheObject(ACCESS_TOKEN_KEY, accessToken, 7000, TimeUnit.SECONDS);
        return accessToken;
    }

    /**
     * 从微信接口获取access_token并缓存到Redis
     */
    private String fetchAccessTokenFromWechat() {
        try {
            // 构建请求URL
            String url = String.format(ACCESS_TOKEN_URL, appId, secret);

            String res = HttpUtils.sendGet(url);
            JSONObject wxAccessToken = JSONObject.parse(res);
            // System.out.println(wxAccessToken);
            return wxAccessToken.getString("access_token");
        } catch (Exception e) {
            throw new RuntimeException("获取access_token异常: " + e.getMessage(), e);
        }
    }

    /**
     * 微信access_token响应的实体类
     */
    public static class WechatTokenResponse {
        private String access_token;
        private Integer expires_in;
        private Integer errcode;
        private String errmsg;

        // getter和setter方法
        public String getAccess_token() {
            return access_token;
        }

        public void setAccess_token(String access_token) {
            this.access_token = access_token;
        }

        public Integer getExpires_in() {
            return expires_in;
        }

        public void setExpires_in(Integer expires_in) {
            this.expires_in = expires_in;
        }

        public Integer getErrcode() {
            return errcode;
        }

        public void setErrcode(Integer errcode) {
            this.errcode = errcode;
        }

        public String getErrmsg() {
            return errmsg;
        }

        public void setErrmsg(String errmsg) {
            this.errmsg = errmsg;
        }
    }
}
